<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/7/22
 * Time: 10:40
 */

namespace app\service;

use phpmailer\BaseException;
use think\Db;
use think\facade\Session;

class BizproService
{
    /**
     * 商品保存
     * @author   juzi
     * @blog     https://blog.csdn.net/juziaixiao
     * @version  1.0.0
     * @datetime 2020年7月21日15:25:02
     * @param    [array]          $params [输入参数]
     */
    public static  function SaveCate($data,$params){
        $standard_desc=$data['standard_desc'];
        unset($data['standard_desc']);
        //BizproService::VaryData($data);

        // 添加/编辑
//        Db::startTrans();
        $bizproId='';
        if (empty($params['id']))
        {



            #调用从富文本编辑器中获取图片
            #有图片 处理
          /*  $imgname = imgName($data['detail']);
            if(!empty($imgname[0])){
                //处理多余图片
                $in_use =array_map('wipeOffFormStr',get_images_from_html($data['detail']));
                # 无用图片清理
                $banner_url=explode(',',$data['banner']);
                array_push($banner_url,$data['imgurl']);

                $_img_res=array_merge($banner_url,$in_use);
                ResourceService::delCacheItem($_img_res);
                ResourceService::delUploadCache();

            }*/



            #创建
            $bizproId = Db::table('bizpro')->insertGetId($data);
            if(!$bizproId)
            {
//                Db::rollback();
                throw new BaseException(['code'=>403 ,'errorCode'=>'pro001','msg'=>'添加商品失败','status'=>false,'debug'=>false]);
            }

            $re=Db::name('standard_detail')->insertGetId(['standard_desc'=>$standard_desc,'bizpro_id'=>$bizproId]);
            if(!$re)
            {
//                Db::rollback();
                throw new BaseException(['code'=>403 ,'errorCode'=>'pro001','msg'=>'添加商品失败','status'=>false,'debug'=>false]);
            }

            return true;

        } else {
            if(empty($data['imgurl']))
            {
                $data['imgurl']= $data['old_imgurl'];
            }
            unset($data['old_imgurl']);
            if(!empty(get_images_from_html($data['detail']))){
                //处理多余图片
                $in_use =array_map('wipeOffFormStr',get_images_from_html($data['detail']));
                # 无用图片清理
                $banner_url=explode(',',$data['banner']);
                array_push($banner_url,$data['imgurl']);
                $_img_res=array_merge($banner_url,$in_use);
                ResourceService::delCacheItem($_img_res);
                ResourceService::delUploadCache();

            }

            #编辑规格
            $re = Db::name('bizpro')->where(['id' => intval($params['id'])])->update($data);
            if(!$re)
            {
               // Db::rollback();
                //throw new BaseException(['code'=>403 ,'errorCode'=>'pro002','msg'=>'修改商品失败','status'=>false,'debug'=>false]);
            }
            $is=Db::name('standard_detail')->where('bizpro_id='.intval($params['id']))->value('update_time');

            if(empty($is))
            {
                $re=Db::name('standard_detail')->insertGetId(['standard_desc'=>$standard_desc,'bizpro_id'=>intval($params['id'])]) ;
            }else{
                $re=Db::name('standard_detail')->where('bizpro_id='.intval($params['id']))->update(['standard_desc'=>$standard_desc]);
            }
            if(!$re)
            {
               // Db::rollback();
                //throw new BaseException(['code'=>403 ,'errorCode'=>'pro003','msg'=>'修改商品失败','status'=>false,'debug'=>false]);
            }

        }

//        Db::commit();
        return true;
    }

    /**
     * 数据处理
     * @author   juzi
     * @blog     https://blog.csdn.net/juziaixiao
     * @version  1.0.0
     * @datetime 2020年7月21日15:24:57
     * @param    [array]          $params [输入参数]
     */
    public static function HandleData($params){
        $data = $params;
        #规格处理：规格名称
        $base_name=[];
        for($i=1;$i<=2;$i++)
        {
            if(!empty($params['standard_base_name'.$i]))
            {
                $base_name[$i]=['name'=>$params['standard_base_name'.$i],'value'=>$params['standard_base_value'.$i]];
                //[$this->data_post['standard_base_name1']=>$this->data_post['standard-base-value1']];
            }
            unset($data['standard_base_name'.$i]);
            unset($data['standard_base_value'.$i]);
        }

        $data['standard_base']=json_encode($base_name);

        #规格处理：规格-价格
        $price_arr=[];


        foreach ($params['standard_price_name1'] as $k=>$v)
        {
            if(empty($params['sale_price'][$k])||empty($params['buy_price'][$k]))
            {
                throw new BaseException(['code'=>403 ,'errorCode'=>'30006','msg'=>'规格价格必须填写','status'=>false,'debug'=>false]);
            }
            $value=[];
            if(!empty($v))
            {
                $value['standard_value1']=$v;
            }
            if(!empty($params['standard_price_name2'][$k]))
            {
                $value['standard_value2']=$params['standard_price_name2'][$k];
            }
            $value['buy_price']=$params['buy_price'][$k];
            $value['sale_price']=$params['sale_price'][$k];
            $price_arr[$k]=$value;


        }

        $data['sale_price']=arraySort($price_arr,'sale_price','asc')[0]['sale_price'];
        unset($data['standard_price_name1']);
        unset($data['standard_price_name2']);
        unset($data['buy_price']);
        unset($data['sale_price']);
        $data['standard_desc']=json_encode($price_arr);
        # 参数处理
        # 处理参数
        $bizpro_params=[];
        foreach ($params['params_title'] as $k=>$v)
        {
            $bizpro_params[$k]=['title'=>$v,'params'=>$params['params'][$k]];
        }

        $data['params']=json_encode($bizpro_params);
        #删除多余字段
        unset($data['params_title']);

        unset($data['thumb_img'],$data['activeBanner']);
        $data['imgurl']=str_replace('/upload/','',$data['imgurl']);
        return $data;
    }
    /**
     * 商品数据校验 添加 修改
     * @author   juzi
     * @blog    https://blog.csdn.net/juziaixiao
     * @version 1.0.0
     * @date    2020年7月21日13:29:33
     * @param    [array]          $params [输入参数]
     */
    public static function VaryData($params)
    {
        // 请求参数
        $p = [
            [
                'checked_type' => 'empty',
                'key_name' => 'class_id',
                'error_msg' => '请选择商品分类',
                'error_code' => 'pro003',
            ],
            [
                'checked_type' => 'empty',
                'key_name' => 'supplier_id',
                'error_msg' => '请选择供应商',
                'error_code' => 'pro004',
            ],
            [
                'checked_type' => 'empty',
                'key_name' => 'imgurl',
                'error_msg' => '缩略图不能为空',
                'error_code' => 'pro005',
            ],
            [
                'checked_type' => 'empty',
                'key_name' => 'banner',
                'error_msg' => 'banner不能为空',
                'error_code' => 'pro006',
            ],


        ];

        $ret=ParamsChecked($params, $p);

        if(true !== $ret)
        {

            //$error_arr[0]  $error_arr[1]
            $error_arr = explode(',', $ret);
            throw new BaseException(['code'=>403 ,'errorCode'=>$error_arr[1],'msg'=>$error_arr[0],'status'=>false,'debug'=>false ]);
        }

        //位置重复判断
        return true ;
    }

    /**
     * 商品数据校验 添加 修改
     * @author   juzi
     * @blog    https://blog.csdn.net/juziaixiao
     * @version 1.0.0
     * @date    2020年7月21日13:29:33
     * @param    [array]          $params [输入参数]
     */
    public static function BizproList($params)
    {
        $where = empty($params['where']) ? [] : $params['where'];
        $field = empty($params['field']) ? '*' : $params['field'];
        $order_by = empty($params['order_by']) ? 'b.id '. $params['sort'] : trim($params['order_by']).' '. $params['sort'];

        $page = $params['page'] ? true : false;
        $number = isset($params['number']) ? intval($params['number']) : 2;
        $m = isset($params['m']) ? intval($params['m']) : 0;
        $n = isset($params['n']) ? intval($params['n']) : 0;

        #随机数据
        if($params['rand'])
        {
            $rand=Db::name('bizpro')->alias('b')->join(['standard_detail'=>'sd'], 'b.id=sd.bizpro_id')->field($field)
                ->orderRand()->limit(20)->select();

            return self::BizDataDealWith($rand,$params);
        }

        $data = Db::name('bizpro')->alias('b')->leftJoin(['standard_detail'=>'sd'], 'b.id=sd.bizpro_id')->field($field)->where($where)->order($order_by);

        if($page)
        {
            $data=$data->paginate($number, false, ['query' => request()->param()]);
            $params['currentPage']=$data->currentPage();
            $params['lastPage']=$data->lastPage();
            $params['total']=$data->total();
            $data=$data->toArray()['data'];

        }else{
            if($n){
                $data=$data->limit($m, $n)->select();

            }else{
                $data=$data->select();
            }

        }


        $re=self::BizDataDealWith($data,$params);
        $re['page']=[];
        if($page)
        {
            $re['page']['currentPage']= $params['currentPage'];
            $re['page']['lastPage']=$params['lastPage'];
            $re['page']['total']=$params['total'];
            $re['page']['per_page']=$number;
        }


        return $re;

    }

    /**
     * 商品数据处理
     * @author   juzi
     * @blog    https://blog.csdn.net/juziaixiao
     * @version 1.0.0
     * @date    2020年7月21日13:29:33
     * @desc    description
     * @param   [array]          $data [商品分类数据 二维数组]
     */
    public static function BizDataDealWith($data,$params=[]){



        if(!empty($data) && is_array($data))
        {

            foreach($data as &$v)
            {

                if(isset($v['imgurl']))
                {
                    $v['imgurl'] = ResourceService::AttachmentPathViewHandle($v['imgurl'],false);
                }

                # 商品标签
                if(isset($v['label'])&&!empty($v['label']))
                {
                    $v['label'] = explode(',',$v['label']);
                }

                #商品详情
                if(isset($v['banner']))
                {
                    $v['banner']=explode(',',$v['banner']);
                    $v['banner']=array_map(function ($re){
                        return ResourceService::AttachmentPathViewHandle($re,false);
                    },$v['banner']);

                }

                #商品运费
                if(isset($v['express_price']))
                {
                    $v['express_price']=$v['express_price']==0?'包邮': $v['express_price'];
                }

                #商品规格名称standard_base
                if(isset($v['standard_base'])&&!empty($v['standard_base']))
                {
                    $v['standard_base']=json_decode($v['standard_base'],true);

                }
                #商品规格价格standard_desc
                if(isset($v['standard_desc'])&&!empty($v['standard_desc']))
                {
                    $v['standard_desc'] = json_decode($v['standard_desc'],true);

                }
                # 商品售价
                if(isset($v['standard_desc'])&&!empty($v['standard_desc']))
                {

                    $arr=arraySort($v['standard_desc'],'sale_price','asc');
                    $v['sale_price'] = number_format($arr[0]['sale_price'],2);
                    $v['sale_price_max'] = number_format($arr[count($arr)-1]['sale_price'],2);
                }
                #商品参数
                if(isset($v['params']))
                {
                    $v['param_arr']=json_decode($v['params'],true);
                    unset($v['params']);
                }

                # 上品销量
                if(isset($v['real_num']))
                {
                    $v['real_num']=$v['real_num']+$v['fake_num'];
                }
                # 上品详情
                if(isset($v['detail']))
                {
                    $v['detail']=ResourceService::ContentStaticReplace($v['detail']);
                }


            }

           # 有rand不排序
            if(empty($params['rand'])){
                $order_by = empty($params['order_by']) ? 'b.id '. $params['sort'] : trim($params['order_by']).' '. $params['sort'];
                if(explode(' ',$order_by)[0]=='b.sale_price')
                {
                    $data=arraySort($data,'sale_price',explode(' ',$order_by)[1]);
                }
            }




        }
        return DataReturn('获取成功',0,$data);
    }


    /**
     * 供应商列表条件
     * @author   juzi
     * @blog    https://blog.csdn.net/juziaixiao
     * @version  0.0.1
     * @datetime 2020年7月24日13:22:12
     * @param    [array]          $params [输入参数]
     */
    public static function BizListWhere($params = [])
    {

        $where = [];
        if(!empty($params['keywords']))
        {
            $where[] =['b.name', 'like', '%'.$params['keywords'].'%'];
        }
        $where[]=['b.status', '=', 1];
//        // 状态
        //专区
        if(isset($v['spearea_id'])&&!empty($v['spearea_id']))
        {
            $v['spearea_id'] = explode(',',$v['spearea_id']);
        }
        if(isset($params['spearea_id']) && $params['spearea_id'] > -1)
        {
            $where[] = ['spearea_id', '=', intval($params['spearea_id'])];
        }

        if(isset($params['class_id']) && $params['class_id'] > -1)
        {
            $where[] = ['class_id', '=', intval($params['class_id'])];
        }

        if(isset($params['class_pid']) && $params['class_pid'] > -1)
        {
            $where[] = ['class_pid', '=', intval($params['class_pid'])];
        }

        return $where;
    }

    /**
     * 根据规格查询价位
     * @author   juzi
     * @blog    https://blog.csdn.net/juziaixiao
     * @version  0.0.1
     * @datetime 2020年7月24日13:22:12
     * @param    [array]          $params [输入参数]
     */
    public static function StandardPrice($params){
        $re = Db::name('standard_detail')->field('standard_desc')->where('bizpro_id='.$params['bizpro_id'])->find();
        $re = json_decode($re['standard_desc'],true);
        $params['standard_value1']=isset($params['standard_value1'])?$params['standard_value1']:'';
        $params['standard_value2']=isset($params['standard_value2'])?$params['standard_value2']:'';
        $sale_price = -1;
        $buy_price  = -1;
        foreach ($re as &$v){
            if(!isset($v['standard_value1']))
            {
                $v['standard_value1']='';
            }
            if(!isset($v['standard_value2']))
            {
                $v['standard_value2']='';
            }

            if(in_array($params['standard_value1'],$v) )
            {
                if(in_array($params['standard_value2'],$v))
                {
                    $sale_price = number_format($v['sale_price'],2);
                    $buy_price = number_format($v['buy_price'],2);
                    break;
                }

            }

        }

        if($sale_price<0)
        {

            throw new BaseException(['code'=>403 ,'errorCode'=>'5001','msg'=>'规格参数错误','status'=>false,'debug'=>false]);
        }
        return DataReturn('获取成功',0,['sale_price'=>$sale_price,'buy_price'=>$buy_price]);
    }

    /**
     * 修改商品信息
     * @author   juzi
     * @blog    https://blog.csdn.net/juziaixiao
     * @version  0.0.1
     * @datetime 2020年7月24日13:22:12
     * @param    [array]          $params [输入参数]
     */
    public static function SaveInfo()
    {

    }
}